﻿using System;
using System.IO;
using System.Security.Cryptography;
using System.Text;

namespace YinLongTool.Security
{
	public class MD5Helper
	{
		public static string EnCode(string text, string codepage = "utf-8")
		{
			byte[] bytes = System.Text.Encoding.GetEncoding(codepage).GetBytes(text);
			MD5 mD = new MD5CryptoServiceProvider();
			byte[] value = mD.ComputeHash(bytes);
			return BitConverter.ToString(value).Replace("-", "");
		}
        public static string CalcMd5(string str)
        {
            byte[] bytes = System.Text.Encoding.UTF8.GetBytes(str);
            return CalcMd5(bytes);
        }
        public static string CalcMd5(byte[] bytes)
        {
            using (MD5 md5 = MD5.Create())
            {
                byte[] computeBytes = md5.ComputeHash(bytes);
                string result = "";
                for (int i = 0; i < computeBytes.Length; i++)
                {
                    result += computeBytes[i].ToString("X").Length == 1 ? "0" + computeBytes[i].ToString("X") : computeBytes[i].ToString("X");
                }
                return result;
            }
        }

        public static string CalcMd5(Stream stream)
        {
            using (MD5 md5 = MD5.Create())
            {
                byte[] computeBytes = md5.ComputeHash(stream);
                string result = "";
                for (int i = 0; i < computeBytes.Length; i++)
                {
                    result += computeBytes[i].ToString("X").Length == 1 ? "0" + computeBytes[i].ToString("X") : computeBytes[i].ToString("X");
                }
                return result;
            }
        }
    }
}
